import axios from 'axios';
import {
  UnifiedAnalysisRequest,
  UnifiedAnalysisResult,
  DatabaseType,
  SqlExample,
  AIAnalysisResponse,
  CompatibilityIssue
} from '../types/analysis';

// 配置基础URL - 开发环境直接访问后端端口
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || '/api';

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 创建公开访问的axios实例（不需要认证）
const publicApiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 公开API客户端的响应拦截器
publicApiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      const { status, data } = error.response;
      if (status === 401) {
        console.warn('Public API访问被拒绝，但这不应该发生');
        return Promise.reject(new Error('访问被拒绝'));
      } else if (status >= 500) {
        console.error('服务器错误:', data);
        return Promise.reject(new Error(data?.message || '服务器内部错误'));
      } else {
        return Promise.reject(new Error(data?.message || `请求失败: ${status}`));
      }
    } else if (error.request) {
      console.error('网络错误:', error.request);
      return Promise.reject(new Error('网络连接失败，请检查网络状态'));
    } else {
      console.error('请求配置错误:', error.message);
      return Promise.reject(new Error('请求配置错误'));
    }
  }
);

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('token');
    if (token) {
      (config.headers as any)['Authorization'] = `Bearer ${token}`;
    }

    // 添加用户ID（如果还没有设置的话）
    if (!config.headers?.['X-User-ID']) {
      try {
        const userInfoStr = localStorage.getItem('userInfo');
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          (config.headers as any)['X-User-ID'] = userInfo.id.toString();
        }
      } catch (error) {
        console.warn('Failed to parse user info for X-User-ID header');
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response;

      if (status === 401) {
        // 未授权，清除token并跳转到登录页
        localStorage.removeItem('token');
        window.location.href = '/login';
      }

      // 抛出包含错误信息的Error
      const errorMessage = data?.message || `请求失败 (${status})`;
      throw new Error(errorMessage);
    } else if (error.request) {
      // 网络错误
      throw new Error('网络连接失败，请检查网络设置');
    } else {
      // 其他错误
      throw new Error(error.message || '请求失败');
    }
  }
);

// 健康检查接口
export const healthCheck = (): Promise<ApiResponse<any>> => {
  return apiClient.get('/status');
};

export const getStatus = () => {
  return apiClient.get('/status');
};

export const ping = () => {
  return apiClient.get('/ping');
};

// 仪表盘统计接口
export interface TaskStatistics {
  totalTasks: number;
  completedTasks: number;
  runningTasks: number;
  failedTasks: number;
  pendingTasks: number;
}

export interface SqlStatementStatistics {
  totalStatements: number;
  statementsByType: Record<string, number>;
  statementsBySource: Record<string, number>;
  ddlStatements: number;
  queryStatements: number;
  dmlStatements: number;
}

export interface IssueStatistics {
  totalIssues: number;
  highSeverityIssues: number;
  mediumSeverityIssues: number;
  lowSeverityIssues: number;
  infoIssues: number;
  issuesByCategory: Record<string, number>;
}

export interface RuleStatistics {
  totalRules: number;
  activeRules: number;
  inactiveRules: number;
  rulesByCategory: Record<string, number>;
  rulesBySeverity: Record<string, number>;
}

export interface RecentTask {
  id: number;
  taskName: string;
  taskType: string;
  status: string;
  progress: number;
  createdAt: string;
  updatedAt: string;
  sqlStatementCount: number;
  issueCount: number;
}

export interface SystemStatus {
  serviceStatus: string;
  serviceVersion: string;
  databaseStatus: string;
  lastUpdateTime: string;
  healthCheckStatus: boolean;
}

export interface DashboardStatistics {
  taskStatistics: TaskStatistics;
  sqlStatementStatistics: SqlStatementStatistics;
  issueStatistics: IssueStatistics;
  ruleStatistics: RuleStatistics;
  recentTasks: RecentTask[];
  systemStatus: SystemStatus;
}

export const getDashboardStatistics = (userId?: number): Promise<ApiResponse<DashboardStatistics>> => {
  const params = userId ? `?userId=${userId}` : '';
  return apiClient.get(`/dashboard/statistics${params}`);
};

export const getTaskStatistics = (userId?: number): Promise<ApiResponse<TaskStatistics>> => {
  const params = userId ? `?userId=${userId}` : '';
  return apiClient.get(`/dashboard/task-statistics${params}`);
};

export const getSqlStatistics = (userId?: number): Promise<ApiResponse<SqlStatementStatistics>> => {
  const params = userId ? `?userId=${userId}` : '';
  return apiClient.get(`/dashboard/sql-statistics${params}`);
};

export const getRecentTasks = (limit: number = 5, userId?: number): Promise<ApiResponse<RecentTask[]>> => {
  const params = new URLSearchParams();
  params.append('limit', limit.toString());
  if (userId) params.append('userId', userId.toString());
  return apiClient.get(`/dashboard/recent-tasks?${params.toString()}`);
};

// 手动SQL分析接口
export interface ManualSqlAnalysisRequest {
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  taskName?: string;
  analysisEngine?: string; // RULE_BASED, LLM_BASED, HYBRID
  enableLLMAnalysis?: boolean;
  enableRuleOptimization?: boolean;
}

export interface SqlStatement {
  content: string;
  sourceType: string;
  sqlType: string;
  lineNumber?: number;
  columnNumber?: number;
  className?: string;
  methodName?: string;
  isNativeQuery?: boolean;
  isDerivedQuery?: boolean;
}

export interface ManualSqlAnalysisResponse {
  success: boolean;
  errorMessage?: string;
  sqlStatements: SqlStatement[];
  issues: CompatibilityIssue[];
  totalIssues: number;
  highSeverityCount: number;
  mediumSeverityCount: number;
  lowSeverityCount: number;
  analysisTime: string;
  savedTaskId?: number;
}

export const analyzeSql = (request: ManualSqlAnalysisRequest): Promise<ApiResponse<ManualSqlAnalysisResponse>> => {
  return apiClient.post('/manual-sql/analyze', request);
};

export const saveAnalysisTask = (request: ManualSqlAnalysisRequest): Promise<ApiResponse<number>> => {
  return apiClient.post('/manual-sql/save', request);
};

export const getAnalysisTask = (id: number) => {
  return apiClient.get<ApiResponse<any>>(`/manual-sql/${id}`);
};

// 扫描任务接口
export interface CreateScanTaskRequest {
  taskName: string;
  taskType: string;
  projectId?: number;
  branchName?: string;
  description?: string;
  config?: Record<string, any>;
}

// 使用临时凭据创建扫描任务的请求接口
export interface CreateScanTaskWithCredentialsRequest {
  taskName: string;
  taskType: string;
  projectId?: number;
  branchName?: string;
  description?: string;
  aiEnhancementEnabled?: boolean;
  config?: Record<string, any>;

  // AI筛选配置
  aiSeverityThreshold?: string;
  aiMaxStatements?: number;
  aiTimeoutSeconds?: number;

  // Git相关的临时凭据
  gitAuthMode?: 'PERSONAL_TOKEN';
  gitPlatform?: 'GITLAB' | 'GITEE' | 'GITHUB';
  gitRepositoryUrl?: string;
  personalAccessToken?: string;
  credentialExpirationMinutes?: number;

  // 数据库相关的临时凭据
  enableDatabaseScan?: boolean;
  databaseHost?: string;
  databasePort?: number;
  databaseName?: string;
  databaseSchema?: string;
  databaseUsername?: string;
  databasePassword?: string;
}

export interface ScanTaskResponse {
  id: number;
  taskName: string;
  taskType: string;
  status: string;
  progress: number;
  projectId?: number;
  projectName?: string;
  branchName?: string;
  userId: number;
  username?: string;
  description?: string;
  startTime?: string;
  endTime?: string;
  errorMessage?: string;
  createdAt: string;
  updatedAt: string;
  configJson?: string; // JSON字符串形式的配置
  config?: any; // 解析后的配置对象（前端处理）
  retryCount?: number; // 当前重试次数
  maxRetryCount?: number; // 最大重试次数
  // 新增增强显示字段（后端提供，避免前端重复解析）
  analysisEngineDisplay?: string;  // "AI引擎" | "规则引擎" | "混合模式" 
  dataSourceDisplay?: string;      // "ORACLE: 168.63.18.127:1521/servdb"
  sourceDbType?: string;           // "ORACLE"
  targetDbType?: string;           // "GOLDENDB"
  lastRetryTime?: string;          // 最后重试时间
  canRetry?: boolean;              // 是否可以重试
}

export const createScanTask = (request: CreateScanTaskRequest): Promise<ApiResponse<ScanTaskResponse>> => {
  return apiClient.post('/scan-tasks', request);
};

export const createScanTaskWithCredentials = (request: CreateScanTaskWithCredentialsRequest): Promise<ApiResponse<ScanTaskResponse>> => {
  return apiClient.post('/scan-tasks/with-credentials', request);
};

export const getScanTask = (id: number): Promise<ApiResponse<ScanTaskResponse>> => {
  return apiClient.get(`/scan-tasks/${id}`);
};

// 公开访问任务详情（不需要认证）
export const getScanTaskPublic = (id: number): Promise<ApiResponse<ScanTaskResponse>> => {
  return publicApiClient.get(`/scan-tasks/public/${id}`);
};

export const getUserScanTasks = (userId: number, current: number = 1, size: number = 10): Promise<ApiResponse<any>> => {
  return apiClient.get(`/scan-tasks/user/${userId}?current=${current}&size=${size}`);
};

export const deleteScanTask = (taskId: number): Promise<ApiResponse<void>> => {
  return apiClient.delete(`/scan-tasks/${taskId}`);
};

export const updateTaskStatus = (id: number, status: string, progress?: number): Promise<ApiResponse<ScanTaskResponse>> => {
  const params = new URLSearchParams({ status });
  if (progress !== undefined) {
    params.append('progress', progress.toString());
  }
  return apiClient.put(`/scan-tasks/${id}/status?${params}`);
};

export const startTask = (id: number): Promise<ApiResponse<void>> => {
  return apiClient.post(`/scan-tasks/${id}/start`);
};

export const cancelTask = (id: number): Promise<ApiResponse<void>> => {
  return apiClient.post(`/scan-tasks/${id}/cancel`);
};

export const retryTask = (id: number): Promise<ApiResponse<ScanTaskResponse>> => {
  return apiClient.post(`/scan-tasks/${id}/retry`);
};

export const canRetryTask = (id: number): Promise<ApiResponse<any>> => {
  return apiClient.get(`/scan-tasks/${id}/can-retry`);
};

// 检查任务凭证有效期
export const checkTaskCredentials = (id: number): Promise<ApiResponse<{
  hasValidCredentials: boolean;
  gitCredentialValid: boolean;
  databaseCredentialValid: boolean;
  gitTokenExpiredAt?: string;
  databaseTokenExpiredAt?: string;
}>> => {
  return apiClient.get(`/scan-tasks/${id}/check-credentials`);
};

export const deleteTask = (id: number): Promise<ApiResponse<void>> => {
  return apiClient.delete(`/scan-tasks/${id}`);
};

export const getRunningTasks = (): Promise<ApiResponse<ScanTaskResponse[]>> => {
  return apiClient.get('/scan-tasks/running');
};

// 扫描结果（实际接口）
export interface TaskScanResultsIssue {
  ruleId: string;
  ruleName: string;
  issueType?: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO' | string;
  description?: string;
  suggestion?: string;
  sqlContent?: string;
  sourceFile?: string;
  fileName?: string;
  gitFileUrl?: string;
  lineNumber?: number;
  columnNumber?: number;
  originalSql?: string;
  suggestedSql?: string;
  statementNumber?: number;  // SQL语句编号
  metadata?: {
    analysisEngine?: 'RULE_BASED' | 'LLM_BASED';
    analysisSource?: 'RULE' | 'LLM';
    confidence?: number;
    statementNumber?: number;  // 备选的语句编号位置
    [key: string]: any;
  };
}

export interface TaskScanResults {
  totalFiles: number;
  sqlStatements: number;
  problemSqlStatements: number;  // 有问题的SQL语句数量
  issues: TaskScanResultsIssue[];
}

// SQL语句实体类型（对应后端entity.SqlStatement）
export interface SqlStatementEntity {
  id: number;
  taskId: number;
  statementNumber: number;
  content: string;
  contentHash?: string;
  sqlType: 'QUERY' | 'DML' | 'DDL' | 'PROCEDURE' | 'FUNCTION' | 'TRIGGER';
  sourceType: 'MYBATIS_XML' | 'MYBATIS_ANNOTATION' | 'JPA_ANNOTATION' | 'NATIVE_QUERY' | 'MANUAL_INPUT' | 'DDL_SCRIPT';
  ddlType?: 'CREATE_TABLE' | 'CREATE_INDEX' | 'CREATE_VIEW' | 'CREATE_PROCEDURE' | 'CREATE_FUNCTION' | 'CREATE_TRIGGER' | 'ALTER_TABLE' | 'DROP_TABLE' | 'DROP_INDEX' | 'OTHER';
  sourceFile?: string;
  lineNumber?: number;
  columnNumber?: number;
  className?: string;
  methodName?: string;
  javaAnnotationType?: 'QUERY' | 'MODIFYING' | 'NATIVE_QUERY' | 'JPQL' | 'CRITERIA';
  mybatisXmlElement?: 'SELECT' | 'INSERT' | 'UPDATE' | 'DELETE' | 'SQL';
  primaryTable?: string;
  affectedTablesText?: string;
  databaseObjectsJson?: string;
  extractionMetadataJson?: string;
  isNativeQuery?: boolean;
  isDerivedQuery?: boolean;
  createdAt: string;
  updatedAt?: string;
  deleted: boolean;
}

export const getTaskResults = (taskId: number): Promise<ApiResponse<TaskScanResults>> => {
  // 后端建议提供: GET /scan-tasks/{taskId}/results
  return apiClient.get(`/scan-tasks/${taskId}/results`);
};

// 获取任务SQL语句列表
export const getTaskSqlStatements = (taskId: number): Promise<ApiResponse<SqlStatementEntity[]>> => {
  return apiClient.get(`/scan-tasks/${taskId}/sql-statements`);
};

// 获取任务SQL语句列表（包含问题统计）
export const getTaskSqlStatementsWithIssues = (taskId: number): Promise<ApiResponse<SqlStatementWithIssues[]>> => {
  return apiClient.get(`/scan-tasks/${taskId}/sql-statements-with-issues`);
};

// SQL语句包含问题统计的类型定义
export interface SqlStatementWithIssues {
  taskId: number;
  statementNumber: number;
  sqlContent: string;
  sqlType: 'QUERY' | 'DML' | 'DDL' | 'PROCEDURE' | 'FUNCTION' | 'TRIGGER';
  sourceType: 'MYBATIS_XML' | 'MYBATIS_ANNOTATION' | 'JPA_ANNOTATION' | 'NATIVE_QUERY' | 'MANUAL_INPUT' | 'DDL_SCRIPT';
  isNativeQuery?: boolean;

  // Git扫描相关字段
  sourceFile?: string;
  lineNumber?: number;
  className?: string;
  methodName?: string;
  javaAnnotationType?: string;
  mybatisXmlElement?: string;
  gitUrl?: string;

  // DDL扫描相关字段
  ddlType?: string;
  primaryTable?: string;
  affectedTables?: string[];
  databaseObjects?: any;

  // 通用字段
  extractionMetadata?: any;

  // 问题统计字段
  issueCount: number;
  hasIssues: boolean;
  issuesBySeverity: { [severity: string]: number };
}

// 兼容性规则接口
export interface CompatibilityRule {
  id: number;
  ruleId: string;
  ruleName: string;
  category: string;
  sourceDbType: string;
  targetDbType: string;
  rulePattern: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  description: string;
  suggestion: string;
  exampleSql: string;
  suggestedSql: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CompatibilityRulesResponse {
  records: CompatibilityRule[];
  total: number;
  current: number;
  size: number;
}

export const getCompatibilityRules = (params: {
  current: number;
  size: number;
  sourceDbType?: string;
  targetDbType?: string;
  severity?: string;
  category?: string;
  search?: string;
}): Promise<ApiResponse<CompatibilityRulesResponse>> => {
  const searchParams = new URLSearchParams();
  searchParams.append('current', params.current.toString());
  searchParams.append('size', params.size.toString());

  if (params.sourceDbType) searchParams.append('sourceDbType', params.sourceDbType);
  if (params.targetDbType) searchParams.append('targetDbType', params.targetDbType);
  if (params.severity) searchParams.append('severity', params.severity);
  if (params.category) searchParams.append('category', params.category);
  if (params.search) searchParams.append('search', params.search);

  return apiClient.get(`/compatibility-rules?${searchParams.toString()}`);
};

// 新增规则管理接口类型定义
export interface CreateRuleRequest {
  ruleId: string;
  ruleName: string;
  category: string;
  sourceDbType: string;
  targetDbType: string;
  rulePattern: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  description: string;
  suggestion: string;
  exampleSql?: string;
  suggestedSql?: string;
  isActive?: boolean;
}

export interface UpdateRuleRequest {
  ruleName: string;
  category: string;
  sourceDbType: string;
  targetDbType: string;
  rulePattern: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  description: string;
  suggestion: string;
  exampleSql?: string;
  suggestedSql?: string;
  isActive?: boolean;
}

export interface BatchUpdateRuleStatusRequest {
  ruleIds: number[];
  isActive: boolean;
}

// 规则管理API接口
export const getCompatibilityRuleById = (ruleId: number): Promise<ApiResponse<CompatibilityRule>> => {
  return apiClient.get(`/compatibility-rules/${ruleId}`);
};

// 根据ruleId获取规则详情
export const getCompatibilityRuleByRuleId = (ruleId: string): Promise<ApiResponse<CompatibilityRule>> => {
  return apiClient.get(`/compatibility-rules/by-rule-id/${ruleId}`);
};

export const createCompatibilityRule = (data: CreateRuleRequest): Promise<ApiResponse<CompatibilityRule>> => {
  return apiClient.post('/compatibility-rules', data);
};

export const updateCompatibilityRule = (ruleId: number, data: UpdateRuleRequest): Promise<ApiResponse<CompatibilityRule>> => {
  return apiClient.put(`/compatibility-rules/${ruleId}`, data);
};

export const toggleCompatibilityRuleStatus = (ruleId: number): Promise<ApiResponse<CompatibilityRule>> => {
  return apiClient.put(`/compatibility-rules/${ruleId}/status`);
};

export const deleteCompatibilityRule = (ruleId: number): Promise<ApiResponse<void>> => {
  return apiClient.delete(`/compatibility-rules/${ruleId}`);
};

export const batchUpdateRuleStatus = (data: BatchUpdateRuleStatusRequest): Promise<ApiResponse<void>> => {
  return apiClient.post('/compatibility-rules/batch-status', data);
};

// 大模型优化接口
export interface LLMOptimizeRequest {
  sql: string;
  sourceDbType: string;
  targetDbType: string;
}

export interface LLMConfig {
  provider: string;
  modelName: string;
  temperature?: number;
  maxTokens?: number;
}

export interface OptimizationHighlight {
  type: 'addition' | 'deletion' | 'modification';
  line: number;
  column: number;
  length: number;
  description: string;
}

export interface LLMCompatibilityIssue {
  type: string;
  severity: 'HIGH' | 'MEDIUM' | 'LOW';
  description: string;
  suggestion: string;
  line?: number;
  column?: number;
}

export interface OptimizationMetadata {
  provider: string;
  modelName: string;
  modelVersion?: string;
  tokensUsed?: number;
  processingTime?: number;
  timestamp: string;
  promptTemplate?: string;
}

export interface LLMOptimizationResult {
  optimizationId?: number;
  originalSql: string;
  optimizedSql: string;
  explanation: string;
  optimizationDetails: string;
  highlights: OptimizationHighlight[];
  issues: LLMCompatibilityIssue[];
  metadata: OptimizationMetadata;
}

export interface ModelInfo {
  name: string;
  displayName: string;
  description: string;
  maxTokens: number;
}

export interface ProviderInfo {
  name: string;
  defaultModel: string;
  models: ModelInfo[];
}

export interface LLMConfigResponse {
  enabled: boolean;
  defaultProvider: string;
  maxRetries: number;
  defaultTimeout: number;
  providers: ProviderInfo[];
  dailyLimit: number;
  minuteLimit: number;
  todayUsage: number;
}

export interface UsageStatistics {
  todayUsage: number;
  canUse: boolean;
}

export interface HealthStatus {
  status: string;
  message: string;
}

export const optimizeSql = (request: LLMOptimizeRequest, userId: number): Promise<ApiResponse<LLMOptimizationResult>> => {
  return apiClient.post(`/llm-optimization/optimize?userId=${userId}`, request);
};

export const getLLMConfig = (userId: number): Promise<ApiResponse<LLMConfigResponse>> => {
  return apiClient.get(`/llm-optimization/config?userId=${userId}`);
};

export const testLLMConnection = (config: LLMConfig): Promise<ApiResponse<boolean>> => {
  return apiClient.post('/llm-optimization/test-connection', config);
};

export const getLLMUsageStatistics = (userId: number): Promise<ApiResponse<UsageStatistics>> => {
  return apiClient.get(`/llm-optimization/usage?userId=${userId}`);
};

export const checkLLMHealth = (): Promise<ApiResponse<HealthStatus>> => {
  return apiClient.get('/llm-optimization/health');
};


// 统一分析接口
export const performUnifiedAnalysis = (request: UnifiedAnalysisRequest): Promise<ApiResponse<UnifiedAnalysisResult>> => {
  return apiClient.post('/analysis/unified', request);
};

// 获取支持的数据库类型
export const getSupportedDatabases = (): Promise<ApiResponse<DatabaseType[]>> => {
  return apiClient.get('/analysis/databases');
};

// 获取SQL示例
export const getSqlExamples = (category?: string, sourceDbType?: string): Promise<ApiResponse<SqlExample[]>> => {
  const params = new URLSearchParams();
  if (category) params.append('category', category);
  if (sourceDbType) params.append('sourceDbType', sourceDbType);

  return apiClient.get(`/analysis/sql-examples?${params.toString()}`);
};

// 验证SQL语法
export const validateSqlSyntax = (sql: string, dbType: string): Promise<ApiResponse<{
  valid: boolean;
  errors: Array<{
    line: number;
    column: number;
    message: string;
  }>;
}>> => {
  return apiClient.post('/analysis/validate', { sqlContent: sql, dbType });
};

// 格式化SQL
export const formatSql = (sql: string, dbType: string): Promise<ApiResponse<{
  success: boolean;
  formattedSql: string;
  errorMessage?: string;
  duration: number;
}>> => {
  return apiClient.post('/analysis/format', { sqlContent: sql, dbType });
};

// 新的AI分析接口 - 语句级分析
export interface UnifiedAIAnalysisRequest {
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  userId?: number;
  rules?: CompatibilityRuleInfo[];  // 新增：传递规则信息
}

// 兼容性规则信息 - 用于AI分析
export interface CompatibilityRuleInfo {
  id: string;                      // 规则的内部数据库ID
  ruleId: string;                  // 规则编号（如RULE001，全局唯一）
  ruleName: string;                // 规则名称
  category: string;                // 规则分类
  sourceDbType: string;            // 源数据库类型
  targetDbType: string;            // 目标数据库类型
  rulePattern: string;             // 规则模式
  severity: 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
  description: string;             // 规则描述
  suggestion: string;              // 建议
  exampleSql: string;              // 示例SQL
  suggestedSql: string;            // 建议SQL
}

// AI分析结果转换为统一格式的辅助函数
export const convertAIResultToUnified = (
  aiResult: AIAnalysisResponse,
  sourceDbType: string,
  targetDbType: string
): CompatibilityIssue[] => {
  const issues: CompatibilityIssue[] = [];

  aiResult.statementAnalysis.forEach(statement => {
    statement.issues.forEach((issue, index) => {
      issues.push({
        id: `ai_${statement.statementNumber}_${index}`,
        statementNumber: statement.statementNumber,
        ruleId: issue.ruleId || `AI${String(statement.statementNumber).padStart(2, '0')}${String(index + 1).padStart(2, '0')}`, // 优先使用规则编号，否则生成虚拟ID
        ruleName: issue.ruleName,
        issueType: issue.category,
        severity: issue.severity,
        category: issue.category,
        description: issue.description,
        suggestion: issue.suggestion,
        sqlContent: statement.originalStatement,
        sqlFragment: issue.problemFragment,
        lineNumber: 1, // 暂时设为1，后续可以通过文本匹配计算
        columnNumber: 1,
        analysisSource: 'LLM',
        confidence: issue.confidence,
        originalCode: issue.problemFragment,
        suggestedCode: issue.suggestedFragment
      });
    });
  });

  return issues;
};

// 通用API响应类型
export interface ApiResponse<T> {
  success: boolean;
  message: string;
  data: T;
  errorCode?: string;
}

// 数据库连接测试请求类型
export interface DatabaseConnectionTestRequest {
  host: string;
  port: number;
  database: string;
  schema?: string;
  username: string;
  password: string;
  dbType: string;
  oracleConnectionType?: string;
}

// 数据库连接测试响应类型
export interface DatabaseConnectionTestResponse {
  success: boolean;
  message: string;
  databaseVersion?: string;
  normalizedVersion?: string;
}

// 数据库连接测试
export const testDatabaseConnection = (request: DatabaseConnectionTestRequest): Promise<ApiResponse<DatabaseConnectionTestResponse>> => {
  return apiClient.post('/database/test-connection', request);
};

// 下载Excel报告
export const downloadExcelReport = async (taskId: number): Promise<Blob> => {
  const response = await apiClient.get(`/reports/task/${taskId}/excel`, {
    responseType: 'blob'
  });
  return response as unknown as Blob;
};

export default apiClient;